import type { MockMethod } from 'vite-plugin-mock'
import Mock from 'mockjs'
import dotenv from 'dotenv'
import svgCaptcha from 'svg-captcha'

// node环境中获取环境变量
dotenv.config({ path: '.env.development' })
const prefix = process.env.VITE_APP_BASE_API

// 响应数据中请求参数的类型
type Recordable<T = any> = Record<string, T>
interface IMockRequest {
  url: string
  body: Recordable
  query: Recordable
  headers: Recordable
}

export default [
  // 账号密码登录
  {
    method: 'post',
    url: `${prefix}/mock/auth/login`,
    response({ body }: IMockRequest) {
      // 从body中解析参数
      const { username, password, captcha } = body
      console.log('账号密码登录body:', body)

      if (!username || !password || !captcha) {
        return {
          code: 1,
          message: '参数错误',
        }
      }

      if (username !== 'admin' || password !== '123456') {
        return {
          code: 1,
          message: '账号或密码错误',
        }
      }

      return {
        code: 0,
        message: '登录成功',
        data: {
          userId: Mock.Random.id(),
          tokenType: 'Bearer',
          accessToken: Mock.Random.guid(),
          refreshToken: Mock.Random.guid(),
          expiresIn: new Date().getTime() + 1000 * 60 * 60 * 24 * 7,
        },
      }
    },
  },
  // 验证码
  {
    method: 'get',
    url: `${prefix}/mock/auth/captcha`,
    response() {
      const captcha = svgCaptcha.createMathExpr({
        size: 4, // 验证码长度
        ignoreChars: '0o1i', // 排除字符
        noise: 3, // 干扰线条数
        color: true, // 彩色验证码
        // background: '#FFFF00', // 背景色
        width: 100,
        height: 40,
      })

      return {
        code: 0,
        message: '验证码生成成功',
        data: {
          text: captcha.text, // 后端可以校验
          svg: captcha.data, // 前端展示 <div v-html="svg" />
        },
      }
    },
  },
] satisfies MockMethod[]
